package com.common.swagger;

import com.common.properties.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(value = SwaggerProperties.class)
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
        ApiSelectorBuilder builder = docket.select();
        builder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
        builder.paths(PathSelectors.any());
        //存储用户必须提交的参数
        SwaggerProperties.Authorization authorization = swaggerProperties.getAuthorization();
        if (null != authorization) {
            String name = authorization.getName();
            if (!StringUtils.hasText(name)) {
                name = authorization.getKeyName();
            }
            List<SecurityScheme> apiKey = new ArrayList<>();
            apiKey.add(new ApiKey(name, authorization.getKeyName(), authorization.getPassAs()));
            docket.securitySchemes(apiKey);
        }
        return builder.build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact(swaggerProperties.getContactName(),
                swaggerProperties.getContactUrl(),
                swaggerProperties.getContactEmail());
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .contact(contact)
                .build();
    }
}